#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/9/19 20:16
# @Author  : Tom_zc
# @FileName: comment-pr.py
# @Software: PyCharm
import base64
import os
import sys
import time
import click
import logging
import yaml

from collections import defaultdict

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, "utils"))
logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")

from utils.gitcode_helper import GitCodeHelper
from utils.parse_params import parse_repo_info_by_webhook_payload, parse_payload_body
from utils.common import func_retry, write_content
from utils.obs_helper import ObsHelper
from utils.pipeline_helper import PipeLineHelper
from utils.majun_helper import MaJunHelper
from utils.poison_helper import PoisonHelper
from utils.sca_helper import SCAHelper
import check_consts


class GitCodeCommentHelper:
    na_status = "N/A"
    link_text = "点此跳转"
    comment_format = '<a href="{}">{}</a>'

    ci_failed_labels = "ci-failed"
    ci_successful_labels = "ci-successful"
    ci_labels = [ci_failed_labels, ci_successful_labels, "ci-running"]

    def __init__(self, domain, owner, repo, pr_number, token):
        self._git_helper = GitCodeHelper(owner, repo, pr_number, token, domain=domain)
        self.pr_info = self._git_helper.get_pr()

    @func_retry()
    def delete_ci_labels(self):
        for label in self.pr_info["labels"]:
            if label["name"] in self.ci_labels:
                self._git_helper.delete_label(label["name"])

    @func_retry()
    def add_ci_result_labels(self, is_successful=True):
        self.pr_info = self._git_helper.get_pr()
        labels = [i["name"] for i in self.pr_info["labels"]]
        if is_successful:
            labels.append(self.ci_successful_labels)
        else:
            labels.append(self.ci_failed_labels)
        self._git_helper.create_label(json_data=labels)

    @func_retry()
    def create_comment(self, comment):
        self._git_helper.create_comment({"body": comment})

    @classmethod
    def to_comment(cls, pipeline_info):
        # to get the comment template
        content = PipeLineLogHelper.read_comment_template("comment.html")
        if "scan" in pipeline_info.keys():
            scan_result = "&#9989;SUCCESS" if pipeline_info["scan"]["status"] == "PASS" else "&#10060;FAILED"
            scan_link = pipeline_info["scan"]["link"]
            line = cls.comment_format.format(scan_link, cls.link_text)
            content = content.replace("{{scan_result}}", scan_result). \
                replace("{{scan_link_text}}", line)
        else:
            content = content.replace("{{scan_result}}", cls.na_status). \
                replace("{{scan_link_text}}", cls.na_status)

        if "poison" in pipeline_info.keys():
            poison_result = "&#9989;SUCCESS" if pipeline_info["poison"]["status"] == "PASS" else "&#10060;FAILED"
            poison_link = pipeline_info["poison"]["link"]
            line = cls.comment_format.format(poison_link, cls.link_text)
            content = content.replace("{{poison_result}}", poison_result). \
                replace("{{poison_link_text}}", line)
        else:
            content = content.replace("{{poison_result}}", cls.na_status). \
                replace("{{poison_link_text}}", cls.na_status)

        if "sca" in pipeline_info.keys():
            sca_result = "&#9989;SUCCESS" if pipeline_info["sca"]["status"] == "PASS" else "&#10060;FAILED"
            sca_link = pipeline_info["sca"]["link"]
            line = cls.comment_format.format(sca_link, cls.link_text)
            content = content.replace("{{sca_result}}", sca_result). \
                replace("{{sca_link_text}}", line)
        else:
            content = content.replace("{{sca_result}}", cls.na_status). \
                replace("{{sca_link_text}}", cls.na_status)

        if "ut" in pipeline_info.keys():
            ut_result = "&#9989;SUCCESS" if pipeline_info["ut"]["status"] == "COMPLETED" else "&#10060;FAILED"
            ut_link = pipeline_info["ut"]["link"]
            line = cls.comment_format.format(ut_link, cls.link_text)
            content = content.replace("{{ut_result}}", ut_result). \
                replace("{{ut_link_text}}", line)
        else:
            content = content.replace("{{ut_result}}", cls.na_status). \
                replace("{{ut_link_text}}", cls.na_status)

        if "it" in pipeline_info.keys():
            it_result = "&#9989;SUCCESS" if pipeline_info["it"]["status"] == "COMPLETED" else "&#10060;FAILED"
            it_link = pipeline_info["it"]["link"]
            line = cls.comment_format.format(it_link, cls.link_text)
            content = content.replace("{{it_result}}", it_result). \
                replace("{{it_link_text}}", line)
        else:
            content = content.replace("{{it_result}}", cls.na_status). \
                replace("{{it_link_text}}", cls.na_status)

        if "coverage" in pipeline_info.keys():
            coverage_result = "&#9989;SUCCESS" if pipeline_info["coverage"][
                                                      "status"] == "COMPLETED" else "&#10060;FAILED"
            coverage_link = pipeline_info["coverage"]["link"]
            line = cls.comment_format.format(coverage_link, cls.link_text)
            content = content.replace("{{coverage_result}}", coverage_result). \
                replace("{{coverage_link_text}}", line)
        else:
            content = content.replace("{{coverage_result}}", cls.na_status). \
                replace("{{coverage_link_text}}", cls.na_status)

        if "build" in pipeline_info.keys():
            build_result = "&#9989;SUCCESS" if pipeline_info["build"]["status"] == "COMPLETED" else "&#10060;FAILED"
            build_link = pipeline_info["build"]["link"]
            line = cls.comment_format.format(build_link, cls.link_text)
            content = content.replace("{{build_result}}", build_result). \
                replace("{{build_link_text}}", line)
        else:
            content = content.replace("{{build_result}}", cls.na_status). \
                replace("{{build_link_text}}", cls.na_status)

        logging.info("pipeline_info:{}".format(pipeline_info.keys()))
        if "vc" in pipeline_info.keys():
            logging.info("vd:::::".format(pipeline_info["vc"]["status"]))
            version_check_result = "&#9989;SUCCESS" if pipeline_info["vc"][
                                                           "status"] == "COMPLETED" else "&#10060;FAILED"
            version_check_link = pipeline_info["vc"]["link"]
            line = cls.comment_format.format(version_check_link, cls.link_text)
            content = content.replace("{{version_check_result}}", version_check_result). \
                replace("{{version_check_link_text}}", line)
        else:
            content = content.replace("{{version_check_result}}", cls.na_status). \
                replace("{{version_check_link_text}}", cls.na_status)

        if "dependency" in pipeline_info.keys():
            dependency_check_result = "&#9989;SUCCESS" if pipeline_info["dependency"][
                                                              "status"] == "COMPLETED" else "&#10060;FAILED"
            version_check_link = pipeline_info["dependency"]["link"]
            line = cls.comment_format.format(version_check_link, cls.link_text)
            content = content.replace("{{dependency_check_result}}", dependency_check_result). \
                replace("{{dependency_check_link_text}}", line)
        else:
            content = content.replace("{{dependency_check_result}}", cls.na_status). \
                replace("{{dependency_check_link_text}}", cls.na_status)

        if "ipmi" in pipeline_info.keys():
            if pipeline_info["ipmi"]["status"] != check_consts.PIPELINE_STATUS.COMPLETED:
                pipeline_info["ipmi"]["status"] = check_consts.PIPELINE_STATUS.WARNING

            ipmi_check_status = pipeline_info["ipmi"]["status"]
            ipmi_check_link = pipeline_info["ipmi"]["link"]
            ipmi_check_result = check_consts.PIPELINE_CONFIG.get_status_icon('ipmi', ipmi_check_status)
            line = cls.comment_format.format(ipmi_check_link, cls.link_text)
            content = content.replace("{{ipmi_check_result}}", ipmi_check_result).replace(
                "{{ipmi_check_link_text}}", line)
        else:
            content = content.replace("{{ipmi_check_result}}", cls.na_status). \
                replace("{{ipmi_check_link_text}}", cls.na_status)

        if "line" in pipeline_info.keys():
            if pipeline_info["line"]["status"] != check_consts.PIPELINE_STATUS.COMPLETED:
                pipeline_info["line"]["status"] = check_consts.PIPELINE_STATUS.WARNING

            line_limit_status = pipeline_info["line"]["status"]
            line_limit_check_link = pipeline_info["line"]["link"]
            line_limit_check_result = check_consts.PIPELINE_CONFIG.get_status_icon('line', line_limit_status)
            line = cls.comment_format.format(line_limit_check_link, cls.link_text)
            content = content.replace("{{line_limit_check_result}}", line_limit_check_result).replace(
                "{{line_limit_check_link_text}}", line)
        else:
            content = content.replace("{{line_limit_check_result}}", cls.na_status). \
                replace("{{line_limit_check_link_text}}", cls.na_status)

        if "model_check" in pipeline_info.keys():
            model_check_status = pipeline_info["model_check"]["status"]
            model_check_link = pipeline_info["model_check"]["link"]
            model_check_result = check_consts.PIPELINE_CONFIG.get_status_icon('model_check', model_check_status)
            line = cls.comment_format.format(model_check_link, cls.link_text)
            content = content.replace("{{model_check_result}}", model_check_result).replace("{{model_check_link_text}}",
                                                                                            line)
        else:
            content = content.replace("{{model_check_result}}", cls.na_status). \
                replace("{{model_check_link_text}}", cls.na_status)

        if "header" in pipeline_info.keys():
            header_status = pipeline_info["header"]["status"]
            header_link = pipeline_info["header"]["link"]
            header_result = check_consts.PIPELINE_CONFIG.get_status_icon('header_check', header_status)
            line = cls.comment_format.format(header_link, cls.link_text)
            content = content.replace("{{header_result}}", header_result).replace("{{header_link_text}}",
                                                                                  line)
        else:
            content = content.replace("{{header_result}}", cls.na_status). \
                replace("{{header_link_text}}", cls.na_status)

        if "smoke_test" in pipeline_info.keys():
            smoke_test_status = pipeline_info["smoke_test"]["status"]
            smoke_test_check_link = pipeline_info["smoke_test"]["link"]
            smoke_test_check_result = check_consts.PIPELINE_CONFIG.get_status_icon('smoke_test', smoke_test_status)
            line = cls.comment_format.format(smoke_test_check_link, cls.link_text)
            content = content.replace("{{smoke_test_result}}", smoke_test_check_result).replace(
                "{{smoke_test_link_text}}", line)
        else:
            content = content.replace("{{smoke_test_result}}", cls.na_status). \
                replace("{{smoke_test_link_text}}", cls.na_status)

        if "robot_it" in pipeline_info.keys():
            if pipeline_info["line"]["status"] != check_consts.PIPELINE_STATUS.COMPLETED:
                pipeline_info["line"]["status"] = check_consts.PIPELINE_STATUS.WARNING

            robot_it_status = pipeline_info["robot_it"]["status"]
            robot_it_check_link = pipeline_info["robot_it"]["link"]
            robot_it_check_result = check_consts.PIPELINE_CONFIG.get_status_icon('robot_it', robot_it_status)
            robot_it_text = cls.comment_format.format(robot_it_check_link, cls.link_text)
            content = content.replace("{{robot_it_result}}", robot_it_check_result).replace(
                "{{robot_it_link_text}}", robot_it_text)
        else:
            content = content.replace("{{robot_it_result}}", cls.na_status). \
                replace("{{robot_it_link_text}}", cls.na_status)
        return content


class PipeLineLogHelper:
    stages_name = "build_test_check"
    pipeline_progress = [
        "build", "ut", "it", "vc", "ipmi", "dependency", "line",
        "model_check", "header", "coverage", "smoke_test", "robot_it"
    ]
    result_status = ["completed", "failed", "warning"]

    js_name = "jquery-3.6.0.min.js"

    def __init__(self, ak, sk, obs_endpoint, obs_static_endpoint, obs_bucket_name, repo, pr_number):
        self._pipeline_helper = PipeLineHelper(ak, sk)
        self._obs_helper = ObsHelper(ak, sk, obs_endpoint)
        self.obs_static_endpoint = obs_static_endpoint
        self.obs_bucket_name = obs_bucket_name
        self.repo = repo
        self.pr_number = pr_number

    def _get_bucket_key(self, job_name, cur_date):
        date_str = time.strftime("%Y_%m_%d_%H_%M_%S", cur_date)
        return "{}/{}/{}_{}.html".format(self.repo, self.pr_number, job_name, date_str)

    def _get_file_path(self, job_name, cur_date):
        date_str = time.strftime("%Y_%m_%d_%H_%M_%S", cur_date)
        return "{}_{}_{}_{}.html".format(self.repo, self.pr_number, job_name, date_str)

    @staticmethod
    def read_comment_template(filename="log.html"):
        path = os.path.join(BASE_DIR, "ci_template", "check", "templates", filename)
        with open(path, "r", encoding="utf-8") as f:
            return f.read()

    def _get_build_log_info(self, project_id, pipeline_id, pipeline_run_id, step):
        """
        1.从step中获取job_id, daily_build_number两个参数
        2.ShowListHistory接口根据job_id和daily_build_number接口找出 build_number
        3.根据build_number和job_id找出record id
        4.根据record_id下载日志文件
        :param step:
        :return:
        """
        job_ids = [step_input["value"] for step_input in step["inputs"] if step_input["key"] == "jobId"]
        job_id = job_ids[0]
        if not step.get("daily_build_number"):
            step_outputs = self._pipeline_helper.show_step_output(project_id, pipeline_id, pipeline_run_id,
                                                                  step["id"])
            daily_build_number_list = [output["value"] for step in step_outputs["step_outputs"] for output in
                                       step["output_result"] if output["key"] == "dailyBuildNumber"]
            if len(daily_build_number_list) == 0:
                return "Get Log Failed, Please comment /retest to try again"
            daily_build_number = daily_build_number_list[0]
        else:
            daily_build_number = step["daily_build_number"]
        build_number = self._pipeline_helper.get_build_number(job_id, daily_build_number)
        build_record_id = self._pipeline_helper.get_build_record_id(job_id, build_number)
        return self._pipeline_helper.download_build_log(build_record_id)

    def _parse_pipeline_detail(self, project_id, pipeline_id, pipeline_run_id, data):
        job_full_name = {
            "build": "build",
            "ut": "unit test",
            "it": "integration test",
            "coverage": "coverage test",
            "vc": "version check",
            "ipmi": "ipmi.json check",
            "dependency": "dependency check",
            "line": "line limit check",
            "model_check": "model check",
            "header": "header check",
            "smoke_test": "smoke test",
            "robot_it": "robot it"
        }
        job_list = list()
        pipeline_info = defaultdict(dict)
        for stage in data["stages"]:
            if stage["name"] == self.stages_name:
                job_list.extend(stage["jobs"])
        job_list = [job for job in job_list if job["name"] in self.pipeline_progress]
        for job in job_list:
            log_info = "=" * 20 + "start to {}".format(job_full_name[job["name"]]) + "=" * 20 + "\r\n"
            for step in job["steps"]:
                if step["name"] in self.pipeline_progress:
                    log_info += self._get_build_log_info(project_id, pipeline_id, pipeline_run_id, step)
                else:
                    log_info += self._pipeline_helper.get_pipeline_log(project_id, pipeline_id, pipeline_run_id,
                                                                       job["id"], step["id"])
                pipeline_info[(job["name"], step["name"])]["log"] = log_info
                pipeline_info[(job["name"], step["name"])]["status"] = step["status"]
        return pipeline_info

    @func_retry()
    def get_pipeline_info(self, project_id, pipeline_id, pipeline_run_id):
        while True:
            pipeline_detail = self._pipeline_helper.get_pipeline_run_detail(project_id, pipeline_id, pipeline_run_id)
            job_list = list()
            for stage in pipeline_detail["stages"]:
                if stage["name"] == self.stages_name:
                    job_list.extend(stage["jobs"])
            job_list = [job for job in job_list if job["name"] in self.pipeline_progress]
            for job in job_list:
                if job["status"].lower() not in self.result_status:
                    logging.info("2.check the pipeline is running...")
                    time.sleep(10)
                    break
                is_step_running = False
                for step in job["steps"]:
                    if step["status"].lower() not in self.result_status:
                        logging.info("3.check the pipeline is running...")
                        time.sleep(10)
                        is_step_running = True
                        break
                if is_step_running:
                    break
            else:
                break
        return self._parse_pipeline_detail(project_id, pipeline_id, pipeline_run_id, pipeline_detail)

    def _get_comment_color_by_status(self, ut_status):
        return "&#9989;" if ut_status == "COMPLETED" else "&#10060;"

    @func_retry()
    def upload_obs(self, pipeline_info, pipeline_detail_dict):
        url_dict = {
            "ut": GitCodeCommentHelper.na_status,
            "it": GitCodeCommentHelper.na_status,
            "coverage": GitCodeCommentHelper.na_status,
            "build": GitCodeCommentHelper.na_status,
            "vc": GitCodeCommentHelper.na_status,
            "ipmi": GitCodeCommentHelper.na_status,
            "dependency": GitCodeCommentHelper.na_status,
            "line": GitCodeCommentHelper.na_status,
            "model_check": GitCodeCommentHelper.na_status,
            "header": GitCodeCommentHelper.na_status,
            "smoke_test": GitCodeCommentHelper.na_status,
            "robot_it": GitCodeCommentHelper.na_status
        }
        status_dict = {
            "ut": GitCodeCommentHelper.na_status,
            "it": GitCodeCommentHelper.na_status,
            "coverage": GitCodeCommentHelper.na_status,
            "build": GitCodeCommentHelper.na_status,
            "vc": GitCodeCommentHelper.na_status,
            "ipmi": GitCodeCommentHelper.na_status,
            "dependency": GitCodeCommentHelper.na_status,
            "line": GitCodeCommentHelper.na_status,
            "model_check": GitCodeCommentHelper.na_status,
            "header": GitCodeCommentHelper.na_status,
            "smoke_test": GitCodeCommentHelper.na_status,
            "robot_it": GitCodeCommentHelper.na_status
        }

        status_str_dict = {
            "ut": GitCodeCommentHelper.na_status,
            "it": GitCodeCommentHelper.na_status,
            "coverage": GitCodeCommentHelper.na_status,
            "build": GitCodeCommentHelper.na_status,
            "vc": GitCodeCommentHelper.na_status,
            "ipmi": GitCodeCommentHelper.na_status,
            "dependency": GitCodeCommentHelper.na_status,
            "line": GitCodeCommentHelper.na_status,
            "model_check": GitCodeCommentHelper.na_status,
            "header": GitCodeCommentHelper.na_status,
            "smoke_test": GitCodeCommentHelper.na_status,
            "robot_it": GitCodeCommentHelper.na_status
        }

        # to get the link url
        cur_date = time.localtime(time.time())
        for job_tuple, log_info in pipeline_info.items():
            bucket_key = self._get_bucket_key(job_tuple[0], cur_date)
            stage = job_tuple[0]
            url_dict[stage] = "{}/{}".format(self.obs_static_endpoint, bucket_key)
            status_dict[stage] = log_info["status"]

        # to upload the log
        logging.info("---pipeline_info.items:{}---".format(pipeline_info.items()))
        for job_tuple, log_info in pipeline_info.items():
            logging.info("---job_tuple:{},pipeline_progress:{}---".format(job_tuple, self.pipeline_progress))
            bucket_key = self._get_bucket_key(job_tuple[0], cur_date)
            content = self.read_comment_template()
            js_url = "{}/{}".format(self.obs_static_endpoint, self.js_name)
            for stage in self.pipeline_progress:
                if status_dict[stage] != GitCodeCommentHelper.na_status:
                    status_str_dict[stage] = self._get_comment_color_by_status(status_dict[stage])

            # link replace
            content = content.replace("{{vc_log_link}}", self.pipeline_progress[3]). \
                replace("{{it_log_link}}", self.pipeline_progress[2]). \
                replace("{{build_log_link}}", self.pipeline_progress[0]). \
                replace("{{dependency_log_link}}", self.pipeline_progress[5]). \
                replace("{{ipmi_log_link}}", self.pipeline_progress[4]). \
                replace("{{line_log_link}}", self.pipeline_progress[6]). \
                replace("{{model_check_log_link}}", self.pipeline_progress[7]). \
                replace("{{header_log_link}}", self.pipeline_progress[8]). \
                replace("{{coverage_log_link}}", self.pipeline_progress[9]). \
                replace("{{smoke_test_log_link}}", self.pipeline_progress[10])

            # url replace
            content = content.replace("{{ut_url}}", url_dict["ut"]). \
                replace("{{it_url}}", url_dict["it"]). \
                replace("{{coverage_url}}", url_dict["coverage"]). \
                replace("{{build_ur}}", url_dict["build"]). \
                replace("{{vc_url}}", url_dict["vc"]). \
                replace("{{dependency_url}}", url_dict["dependency"]). \
                replace("{{ipmi_url}}", url_dict["ipmi"]). \
                replace("{{line_url}}", url_dict["line"]). \
                replace("{{model_check_url}}", url_dict["model_check"]). \
                replace("{{header_check_url}}", url_dict["header"]). \
                replace("{{smoke_test_url}}", url_dict["smoke_test"]). \
                replace("{{robot_it_url}}", url_dict["robot_it"])

            # status replace
            content = content.replace("{{ut_status}}", status_str_dict["ut"]). \
                replace("{{it_status}}", status_str_dict["it"]). \
                replace("{{coverage_status}}", status_str_dict["coverage"]). \
                replace("{{build_status}}", status_str_dict["build"]). \
                replace("{{vc_status}}", status_str_dict["vc"]). \
                replace("{{dependency_status}}", status_str_dict["dependency"]). \
                replace("{{ipmi_status}}", status_str_dict["ipmi"]). \
                replace("{{line_status}}", status_str_dict["line"]). \
                replace("{{model_check_status}}", status_str_dict["model_check"]). \
                replace("{{header_status}}", status_str_dict["header"]). \
                replace("{{smoke_test_status}}", status_str_dict["smoke_test"]). \
                replace("{{robot_it_status}}", status_str_dict["robot_it"])

            # base replace
            content = content.replace("{{log}}", log_info["log"]). \
                replace("{{js_url}}", js_url)
            local_file_path = self._get_file_path(job_tuple[0], cur_date)
            write_content(local_file_path, content.encode("utf-8"))
            self._obs_helper.upload_file(self.obs_bucket_name, bucket_key, local_file_path)
            pipeline_detail_dict[job_tuple[0]] = {
                "status": log_info["status"],
                "link": "{}/{}".format(self.obs_static_endpoint, bucket_key)
            }


class CodeCheckHelper:
    def __init__(self, sca_appId, sca_secretKey, sca_domain):
        self._ma_jun_helper = MaJunHelper(sca_appId, sca_secretKey, sca_domain)

    @func_retry()
    def code_check(self, pr_url, pipeline_detail_dict):
        logging.info("start to create task:{}...".format(pr_url))
        task_id, uuid = self._ma_jun_helper.create_task(pr_url)
        logging.info("start to check task:{}...".format(task_id))
        status, link = self._ma_jun_helper.check_task(task_id, uuid)
        pipeline_detail_dict["scan"] = {
            "status": status,
            "link": link
        }
        logging.info("over to check task....")


class CheckPoisonHelper:
    def __init__(self, sca_appId, sca_secretKey, sca_domain):
        self._poison_helper = PoisonHelper(sca_appId, sca_secretKey, sca_domain)

    @func_retry()
    def poison(self, pr_url, pipeline_detail_dict):
        logging.info("start to create task:{}...".format(pr_url))
        task_id = self._poison_helper.create_task(pr_url)
        logging.info("start to check task:{}...".format(task_id))
        status, link = self._poison_helper.check_task(task_id)
        pipeline_detail_dict["poison"] = {
            "status": status,
            "link": link
        }


class CheckSCAHelper:
    def __init__(self, sca_appId, sca_secretKey, sca_domain):
        self._sca_helper = SCAHelper(sca_appId, sca_secretKey, sca_domain)

    @func_retry()
    def sca(self, pr_url, pipeline_detail_dict):
        logging.info("start to create task:{}...".format(pr_url))
        task_id = self._sca_helper.add_repo(pr_url)
        logging.info("start to check task:{}...".format(task_id))
        status, link = self._sca_helper.check_task(task_id)
        pipeline_detail_dict["sca"] = {
            "status": status,
            "link": link
        }


class RepoConfigHelper:
    """read the config from ci-repos config.yaml"""

    def __init__(self, owner, token, domain, repo="openubmc-ci"):
        self._repo = repo
        self._git_helper = GitCodeHelper(owner, repo, "", token, domain=domain)

    def get_repo_config(self, repo):
        path = "{}/{}/{}".format("ci-repos", repo, "config.yaml")
        resp = self._git_helper.get_contents(path)
        content = base64.b64decode(resp["content"]).decode("utf-8")
        return yaml.safe_load(content)


@click.command()
@click.option("--project_id", help='The project_id of pipeline')
@click.option("--pipeline_id", help='The pipeline_id of pipeline')
@click.option("--pipeline_run_id", help='The pipeline_run_id of pipeline')
def main(project_id, pipeline_id, pipeline_run_id):
    """main"""

    logging.info("=" * 20 + "start to check and comment" + "=" * 20)
    ak = os.getenv("ak")
    sk = os.getenv("sk")
    obs_endpoint = os.getenv("obs_endpoint")
    obs_static_endpoint = os.getenv("obs_static_endpoint")
    obs_bucket_name = os.getenv("obs_bucket_name")
    gitcode_api_domain = os.getenv("gitcode_api_domain")
    sca_appId = os.getenv("sca_appId")
    sca_secretKey = os.getenv("sca_secretKey")
    sca_domain = os.getenv("sca_domain")
    token = os.getenv("gitcode_rw_token")
    gitcode_domain = os.getenv("gitcode_domain")

    if not all([token, ak, sk, obs_endpoint, obs_bucket_name, obs_static_endpoint]):
        logging.info("Lack of params, Please check.")

    owner, repo, branch, pr_number, pr_url = parse_repo_info_by_webhook_payload()

    repo_config_helper = RepoConfigHelper(owner, token, gitcode_api_domain)
    repo_config = repo_config_helper.get_repo_config(repo)

    logging.info("=" * 20 + "start to check codecheck" + "=" * 20)
    pipeline_detail_dict = defaultdict(dict)
    # get the status from codecheck from ma jun
    if repo_config.get("codecheck"):
        code_check_helper = CodeCheckHelper(sca_appId, sca_secretKey, sca_domain)
        try:
            code_check_helper.code_check(pr_url, pipeline_detail_dict)
        except Exception as e:
            logging.error("code check failed:{}".format(e))
            pipeline_detail_dict["scan"] = {
                "status": "FAILED",
                "link": "N/A"
            }

    # get the status from libing
    if repo_config.get("poison"):
        poison_helper = CheckPoisonHelper(sca_appId, sca_secretKey, sca_domain)
        try:
            poison_helper.poison(pr_url, pipeline_detail_dict)
        except Exception as e:
            logging.error("poison check failed:{}".format(e))
            pipeline_detail_dict["poison"] = {
                "status": "FAILED",
                "link": "N/A"
            }

    if repo_config.get("sca"):
        sca_helper = CheckSCAHelper(sca_appId, sca_secretKey, sca_domain)
        pull_url = "{}/{}/{}/pull/{}".format(gitcode_domain, owner, repo, pr_number)
        try:
            sca_helper.sca(pull_url, pipeline_detail_dict)
        except Exception as e:
            logging.error("sca check failed:{}".format(e))
            pipeline_detail_dict["sca"] = {
                "status": "FAILED",
                "link": "N/A"
            }

    logging.info("=" * 20 + "start to get log" + "=" * 20)
    # get the pipeline log from upstream
    pipeline_log_helper = PipeLineLogHelper(ak, sk, obs_endpoint, obs_static_endpoint, obs_bucket_name,
                                            repo, pr_number)
    pipeline_info = pipeline_log_helper.get_pipeline_info(project_id, pipeline_id, pipeline_run_id)
    pipeline_log_helper.upload_obs(pipeline_info, pipeline_detail_dict)

    logging.info("=" * 20 + "start to comment helper" + "=" * 20)

    # start to delete labels and comment and add the labels
    git_code_comment_pr_helper = GitCodeCommentHelper(gitcode_api_domain, owner, repo, pr_number, token)
    comment = git_code_comment_pr_helper.to_comment(pipeline_detail_dict)
    git_code_comment_pr_helper.delete_ci_labels()
    git_code_comment_pr_helper.create_comment(comment)
    success_list = [pipeline_detail for _, pipeline_detail in pipeline_detail_dict.items()
                    if pipeline_detail["status"] in ["COMPLETED", "PASS", "WARNING"]]
    git_code_comment_pr_helper.add_ci_result_labels(len(success_list) == len(pipeline_detail_dict.keys()))

    logging.info("=" * 20 + "end to check and comment" + "=" * 20)


if __name__ == '__main__':
    main()
